<?php
namespace duoge\email;

use Yii;
use yii\swiftmailer\Mailer;


class EmailClient extends \yii\base\BaseObject {

    public $useFileTransport = false;
    public $classname = 'Swift_SmtpTransport';
    public $host;
    public $username;
    public $password;
    public $port;
    public $encryption;
    public $fromaddress;

    private $mailer;

    public function __construct($config = []){
        if(is_object($config)) {
            $config = (array)$config;
        }
        if(key_exists("classname",$config)) {
            $this->classname = $config["classname"];
        }
        if(key_exists("host",$config)) {
            $this->host = $config["host"];
        }
        if(key_exists("username",$config)) {
            $this->username = $config["username"];
        }
        if(key_exists("password",$config)) {
            $this->password = $config["password"];
        }
        if(key_exists("port",$config)) {
            $this->port = $config["port"];
        }
        if(key_exists("encryption",$config)) {
            $this->encryption = $config["encryption"];
        }
        if(key_exists("fromaddress",$config)) {
            $this->fromaddress = $config["fromaddress"];
        }
    }

    /**
     * @return void
     * @throws \yii\base\InvalidConfigException
     */
    private function initMailer() {
        $this->mailer = new Mailer();
        $this->mailer->useFileTransport = $this->useFileTransport;
        $this->mailer->setTransport([
            'class' => $this->classname,
            'host' => $this->host,
            'username' => $this->username,
            'password' => $this->password,
            'port' => $this->port,
            'encryption' => $this->encryption,
        ]);
    }

    /**
     * 发送html邮件
     * @param $to
     * @param $subject
     * @param $body
     * @return bool
     */
    public function send($to,$subject,$body) {
        $this->initMailer();
        return $this->mailer->compose()
        ->setFrom($this->fromaddress)
        ->setTo($to)
        ->setSubject($subject)
        ->setHtmlBody($body)
        ->send();
    }


    /**
     * 发送模版邮件
     * @param $to
     * @param $subject
     * @param $view
     * @param $params
     * @return bool
     */
    public function sendbyview($to,$subject,$view,$params) {
        $this->initMailer();
        return $this->mailer->compose($view,$params)
            ->setFrom($this->fromaddress)
            ->setTo($to)
            ->setSubject($subject)
            ->setHtmlBody(body)
            ->send();
    }
}